// MyAxios.js
import store from "@/store";
import storage from "@/utils/storerage";
import axios from "axios";
import qs from "qs";
import { showNotify } from "vant";
import "vant/es/notify/style";
import LoginApi from "./apis/Login.Api";

// 创建axios实例
const instance = axios.create();
instance.interceptors.request.use((config) => {
  if (localStorage.getItem(storage.KEY.Authorization))
    config.headers.Authorization = localStorage.getItem(
      storage.KEY.Authorization
    );
  return config;
});
instance.interceptors.response.use((config) => {
  if (config.data.code === 404 || config.data.code === 500)
    showNotify({ type: "danger", message: config.data.msg });
  else if (config.data.code === 402) {
    localStorage.removeItem(storage.KEY.Authorization);

    //身份验证过期续签
    let params = store.state.userInfo;
    let checked = storage.localStorageGet(storage.KEY.Checked);
    if (params.accounta !== "" || params.passworda !== "") {
      LoginApi.LoginUser(params).then((res) => {
        console.log(res);
        if (res.data.code === 200) {
          showNotify({ type: "success", message: res.data.msg });
          localStorage.setItem(storage.KEY.Authorization, res.data.token);
          res.data.data.passworda = params.passworda;
          store.commit("updateUserInfo", res.data.data);
          if (checked) {
            localStorage.setItem(storage.KEY.Checked, true);
            storage.localStorageSet(storage.KEY.UserInfo, res.data.data);
            storage.sessionStorageSet(storage.KEY.UserInfo, res.data.data);
          } else {
            localStorage.removeItem(storage.KEY.Checked);
            storage.localStorageRemove(storage.KEY.UserInfo);
            storage.sessionStorageSet(storage.KEY.UserInfo, res.data.data);
          }
        }
      });
    }
  } else if (config.data.code !== 200)
    showNotify({ type: "warning", message: config.data.msg });
  return config;
});

let myaxios = {
  /**
   * 发送get请求
   * @param {string} url  请求路径
   * @param {object} params  请求参数（对象的形式传递）
   * @returns Promise
   */
  get(url, params) {
    return instance({
      url,
      method: "GET",
      params,
    });
  },

  /**
   * 发送post请求
   * @param {string} url  请求路径
   * @param {object} params  请求参数（对象的形式传递）
   * @returns Promise
   */
  post(url, params) {
    return instance({
      url,
      method: "POST",
      data: qs.stringify(params),
    });
  },
};

export default myaxios;
